#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
#define BUFSIZE 100

void read_words_from_stdin(FILE* fp){
    
    char word[MAXWORD];
    char buf[BUFSIZE];
    int sentences = 0;
    int words = 0;
   
    sentences = 0;
    words = 0;
    
    while (1) {
        fscanf(fp, "%s", buf);
        
        if (strcmp(buf,"q")==0)
            break;
        
        printf("%s\n", buf); //for debugging's sake
        words++;
        if( buf[strlen(buf) - 1] == ','){
                     buf[strlen(buf) - 1] = '\0'; //remove half comma from the end
               printf("%s\n", buf); // instead of this, call add_word()
        }
        if (buf[strlen(buf) - 1] == '.') {
            printf("virkkeen loppu\n"); //for debugging's sake
            buf[strlen(buf) - 1] = '\0'; //remove full comma from the end
            printf("%s\n", buf); // instead of this, call add_word()
            sentences++;
        }
    }

//    fclose(fp);
    printf("sentences: %d\n", sentences);
    printf("words: %d\n", words);
    
    
    
    
}

void read_words_from_file(FILE* fp){
    char word[MAXWORD];
    char buf[BUFSIZE];
    int sentences = 0;
    int words = 0;
    
    
    while (1) {
        fscanf(fp, "%s", buf);
        
        if (feof(fp))
            break;
        
        printf("%s\n", buf); //for debugging's sake
        words++;
        if( buf[strlen(buf) - 1] == ','){
                     buf[strlen(buf) - 1] = '\0'; //remove half comma from the end
               printf("%s\n", buf); // instead of this, call add_word()
        }
        if (buf[strlen(buf) - 1] == '.') {
            printf("virkkeen loppu\n"); //for debugging's sake
            buf[strlen(buf) - 1] = '\0'; //remove full comma from the end
            printf("%s\n", buf); // instead of this, call add_word()
            sentences++;
        }
    }

    fclose(fp);
    printf("sentences: %d\n", sentences);
    printf("words: %d\n", words);

}

int main(int argc, char** argv) {

    FILE* fp;
    char word[MAXWORD];
    char buf[BUFSIZE];
    
    
    if (argc == 1) {// Ei parametreja komentoriviltä
        fp = stdin;
        read_words_from_stdin(fp);
    }
    else if (((fp = fopen("testi.txt", "r"))) == NULL) {
        fprintf(stderr, "virhe!");
        return 1;
    }
    else
        read_words_from_file(fp);
 
    return (EXIT_SUCCESS);
}

